﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Soufun.DAL;
using Soufun.DB;

namespace Soufun
{
    public partial class AddHouseTypeForm : DevExpress.XtraEditors.XtraForm
    {
        public AddHouseTypeForm()
        {
            InitializeComponent();
        }

        private DProjectUrl _dProjectUrl = new DProjectUrl();

        private void AddHouseTypeForm_Load(object sender, EventArgs e)
        {
            Thread t = new Thread(LoadProjectUrlList) { IsBackground = true };
            t.Start();
        }

        private void LoadProjectUrlList()
        {
            BeginInvoke(new MethodInvoker(() =>
            {
                comboBox_projectList.Properties.Items.Clear();
            }));
            DataSet ds = _dProjectUrl.GetList("");
            if (ds == null || ds.Tables.Count == 0)
            {
                XtraMessageBox.Show("未能加载项目web列表，请检查数据库连接是否正常！");
                return;
            }
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                string projectName = row["ProjectName"].ToString();
                string projecturl = row["ProjectUrl"].ToString();
                ImageComboBoxItem item = new ImageComboBoxItem();
                item.Description = projectName;
                item.Value = projecturl;
                item.ImageIndex = int.Parse(row["Id"].ToString());
                BeginInvoke(new MethodInvoker(() =>
                {
                    comboBox_projectList.Properties.Items.Add(item);
                }));
            }

        }

        private void btn_excelPath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            openFileDialog1.Filter = "Excel文件|*.xls;*.xlsx";
            openFileDialog1.FileName = "";
            openFileDialog1.ShowDialog();
            string fileName = openFileDialog1.FileName;
            btn_excelPath.Text = fileName;

            gridControl2.DataSource = null;
            gridView2.Columns.Clear();
            gridView2.GroupPanelText = "请选择Excel文件";
            if (fileName == "")
            {
                return;
            }
            DataSet ds = Common.LoadDataFromExcel(fileName);
            if (ds == null || ds.Tables.Count == 0
                || ds.Tables[0].Columns.Count < 4)
            {
                XtraMessageBox.Show("选择的Excel文件数据格式有问题,请核对！");
                btn_excelPath.Text = "";
                return;
            }
            gridControl2.DataSource = ds.Tables[0];
            gridView2.GroupPanelText = "共有" + ds.Tables[0].Rows.Count + "条数据";
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (!CheckInput())
            {
                return;
            }
            comboBox_projectList.Enabled = false;
            btn_excelPath.Enabled = false;
            btn_add.Enabled = false;
            Thread t = new Thread(AddData) { IsBackground = true };
            t.Start();
        }

        private void AddData()
        {
            int projectId = comboBox_projectList.Properties.Items[
                comboBox_projectList.SelectedIndex].ImageIndex;
            DataTable dtOld = (DataTable)gridControl2.DataSource;

            DataTable dt = dtOld.Copy();
            dt.Rows.Clear();
            foreach (DataRow dataRow in dtOld.Rows)
            {
               
                    dt.Rows.Add(dataRow.ItemArray);
                    
            }
           


            int insertRowsCount = 500;//一次性插入数据库行数
            int succeedrows = 0;//成功插入数据行数
            StringBuilder strSql = new StringBuilder();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
              
                if (i % insertRowsCount == 0)
                {
                    strSql = new StringBuilder();
                    strSql.Append("Insert into tProjectHouseTypeInfo (");
                    strSql.Append("ProjectId,UnitID,HouseID,");
                    strSql.Append("HouseArea,HouseType,HouseCount)");
                    strSql.Append(" value  ");
                }
                strSql.Append("(");
                int unitId = 0;
                int houseId = 0;
                float houseArea = 0;
                int houseCount = 0;
                int.TryParse(row[0].ToString(), out unitId);
                int.TryParse(row[1].ToString(), out houseId);
                float.TryParse(row[2].ToString(), out houseArea);
                int.TryParse(row[4].ToString(), out houseCount);

                strSql.Append(projectId);
                strSql.Append(",'");
                strSql.Append(unitId);
                strSql.Append("','");
                strSql.Append(houseId);
                strSql.Append("',");
                strSql.Append(houseArea);
                strSql.Append(",'");
                strSql.Append(row[3]);
                strSql.Append("',");
                strSql.Append(houseCount);
                strSql.Append("),");

                if ((i + 1) % insertRowsCount == 0
                    || i == dt.Rows.Count - 1)
                {
                    strSql.Remove(strSql.Length - 1, 1);
                    succeedrows += DbHelper.ExecuteSql(strSql.ToString());
                }
            }
            
            if (dt.Rows.Count == succeedrows)
            {
                XtraMessageBox.Show("添加成功！");
                BeginInvoke(new MethodInvoker(() =>
                    {
                        btn_excelPath.Text = "";
                        gridControl2.DataSource = null;                        
                    }));
            }
            else
            {
                int failedCount = dt.Rows.Count - succeedrows;
                XtraMessageBox.Show("共记" + dt.Rows.Count + "条数据，其中"
                    + failedCount + "条数据添加失败！");                                
            }
            BeginInvoke(new MethodInvoker(() =>
            {
                comboBox_projectList.Enabled = true;
                btn_excelPath.Enabled = true;
                btn_add.Enabled = true;
            }));
        }

        private bool CheckInput()
        {
            if (comboBox_projectList.SelectedIndex<0)
            {
                XtraMessageBox.Show("请选择项目！");
                comboBox_projectList.Focus();
                return false;
            }
            if (btn_excelPath.Text=="")
            {
                XtraMessageBox.Show("请选择Excel文件！");
                return false;
            }
            return true;
        }
    
    }
}